<template>
  <Sider hide-trigger class="sider-menu">
    <Menu ref="sideMenu" :active-name="$route.name" theme="light" width="auto" @on-select="changeMenu"
          :open-names="openedSubmenuArr">
      <template v-for="item in [...menuList]">
        <MenuItem v-if="item.children.length<=1" :name="item.children[0].name">
          <Icon :type="item.icon" :size="iconSize"></Icon>
          <span class="layout-text">{{ item.meta.title  }}</span>
        </MenuItem>
        <Submenu v-if="item.children.length>1" :name="item.name">
          <template slot="title">
            <Icon :type="item.icon" :size="iconSize"></Icon>
            <span class="layout-text">{{ item.meta.title }}</span>
          </template>
          <template v-for="child in item.children">
            <MenuItem :name="child.name">
              <Icon :type="child.icon" :size="iconSize"></Icon>
              <span class="layout-text">{{ child.meta.title }}</span>
            </MenuItem>
          </template>
        </Submenu>
      </template>
    </Menu>
  </Sider>
</template>

<script>

  export default {
    name: "sider-menu",
    data() {
      return {
        openedSubmenuArr: [],
        iconSize: 14
      }
    },
    props:{
      curPaths:Array
    },
    watch: {
      '$route'() {
        this.changeSubArr()
      }
    },
    components: {},
    computed: {
      menuList(){
        return this.$store.state.routers
      }
    },
    methods: {
      changeSubArr() {
        let routerName = this.$route.name
        let curPaths = [{title:'首页',path:'/home',name:'home_index'}]
        this.menuList.forEach(item => {
          item.children.forEach(child => {
            if (routerName === child.name) {
              if (item.name !== 'otherRouter') {
                if (item.children.length === 1) {
                  if (child.name !== 'home_index')
                    curPaths.push({title:child.meta.title,path:item.path+'/'+child.path,name:child.name})
                } else {
                  curPaths.push({title:item.meta.title,path:item.path,name:item.name}, {title:child.meta.title,path:item.path+'/'+child.path,name:child.name})
                }
                this.openedSubmenuArr = [item.name]
              } else {
                curPaths.push({title:child.meta.title,path:item.path+'/'+child.path,name:child.name})
              }
            }
          })
        })
        this.$emit('on-update-path',curPaths)
        this.$emit('on-cur-route-change',this.$route)
      },
      changeMenu(active) {
        this.$router.push({
          name: active
        });
      }
    }, updated() {
      this.$nextTick(() => {
        if (this.$refs.sideMenu) {
          this.$refs.sideMenu.updateOpened();
        }
      });
    },
    created() {

    },
    mounted() {
      this.changeSubArr()
    }
  }
</script>

<style scoped lang="less">

</style>
